package com.maoyan.base.util;

import java.util.HashMap;
import java.util.Map;

public class ThreadLocalContext {
	private static final ThreadLocal<Map<String, Object>> context = new ThreadLocal<Map<String, Object>>();
	
	/**
	 * 清空线程上下文中缓存的变量.
	 */
	 public static void clear() {
	   context.set(null);
	 }

	 /**
	  * 在线程上下文中缓存变量.
	  */
	 public static void set(String key, Object value) {
	   Map<String, Object> map = (Map<String, Object>) context.get();
	   if (map == null) {
	     map = new HashMap<String, Object>();
	     context.set(map);
	   }
	   map.put(key, value);
	 }

	 /**
	  * 从线程上下文中取出变量.
	  */
	 public static Object get(String key) {
	   Map<String, Object> map = (Map<String, Object>) context.get();
	   Object value = null;
	   if (map != null) {
	     value = map.get(key);
	   }
	   return value;
	 }

	 /**
	  * 将变量移除.
	  */
	 public static void remove(String key) {
	   Map<String, Object> map = (Map<String, Object>) context.get();
	   if (map != null) {
	     map.remove(key);
	   }
	 }
}
